// pages/cardDetail/cardDetail.js
import {
  update_scan,
  ftp_share_image,
  oss_sign,
  baseUrl
} from "../../utils/api.js";
const util = require('../../utils/util.js')
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    TaskShow: 0,
    haveTap: 1, // 1: 可以点击 0：不可点击
    haveShare: 0, // 0：完成/未开始 1：分享
    CarteList: [],
    content: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取名片列表
    const that = this
    let url = '/cardshop_api/queryUsers';
    let params = {
      id: options.id
    }
    app.HttpPostSend(url, params, function (res) {
      if (res.msg != "success") {
        app.showTipMsg(res.msg);
      } else {
        that.setData({
          CarteList: res.data
        })
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  // canvas渲染
  renderCanvasCarte: function (idx, params) {
    const that = this
    // const params = this.data.CarteList[idx]
    const wxGetImageInfo = function (src) {
      let p = new Promise((resolve, reject) => {
        // console.log(server_url + uri)
        wx.getImageInfo({
          src: src,
          success(res) {
            resolve(res)
          },
          fail(err) {
            reject(err)
          },
          complete() {

          }
        })
      })
      return p
    }
    const weGetElementInfo = function (filterArr) {
      let p = new Promise((resolve, reject) => {
        // console.log(server_url + uri)
        const query = wx.createSelectorQuery()
        filterArr.map(items => {
          if (items.type == 1) {
            return query.select(items.content).boundingClientRect()
          } else if (items.type == 2) {
            return query.selectAll(items.content).boundingClientRect()
          }
        })
        query.exec(result => {
          resolve(result)
        })
      })
      return p
    }
    const toTempPath = new Promise((resolve, reject) => {
      Promise.all([
        weGetElementInfo([
          {
            content: '#carte_canvas_' + idx,
            type: 1
          },
          {
            content: '#cardBox_' + idx + ' .cardBox_bg',
            type: 1
          },//背景图
          {
            content: '#cardBox_' + idx + ' .cardBoxTop_left .logo',
            type: 1
          },//公司Logo
          {
            content: '#cardBox_' + idx + ' .cardBoxTop_left .company',
            type: 1
          },//公司名字
          {
            content: '#cardBox_' + idx + ' .cardBoxTop_right .name',
            type: 1
          },//名字
          {
            content: '#cardBox_' + idx + ' .cardBoxTop_right .job .job_text',
            type: 2
          },//职位
          {
            content: '#cardBox_' + idx + ' .cardBoxTop_right .job .job_point',
            type: 1
          },//职位
          {
            content: '#cardBox_' + idx + ' .cardBoxBottom_left .avatar_bg',
            type: 1
          },//头像背景
          {
            content: '#cardBox_' + idx + ' .cardBoxBottom_left .avatar_content .avatar',
            type: 1
          },//头像
          {
            content: '#cardBox_' + idx + ' .contactBox_phone .phone_icon',
            type: 1
          },//电话
          {
            content: '#cardBox_' + idx + ' .contactBox_phone .phone_content',
            type: 1
          },
          {
            content: '#cardBox_' + idx + ' .contactBox_mail .mail_icon',
            type: 1
          },//邮箱
          {
            content: '#cardBox_' + idx + ' .contactBox_mail .mail_content',
            type: 1
          },
        ]),
        wxGetImageInfo(params.com_logo),
        wxGetImageInfo(params.img),
      ]).then(res => {
        // console.log(res)
        let topBorder = res[0][0].top
        let leftBorder = res[0][0].left
        let canvasWidth = res[0][0].width
        let canvasHeight = res[0][0].height
        let getPosition = (type, index, idx) => {
          let aimTop = type == 3 ? res[0][index][idx].top - topBorder : res[0][index].top - topBorder
          let aimLeft = type == 3 ? res[0][index][idx].left - leftBorder : res[0][index].left - leftBorder
          if (type == 0 || type == 3) {
            return [aimLeft, aimTop]
          } else if (type == 1) {
            return [res[0][index].width, res[0][index].height]
          } else if (type == 2) {
            return [aimLeft, aimTop, res[0][index].width, res[0][index].height]
          }
        }
        const ctx = wx.createCanvasContext('carte_canvas_' + idx)
        // 背景图
        ctx.drawImage('https://mpian.oss-cn-hangzhou.aliyuncs.com/mingpian/20190522/0fa66799d95b7157d8145af56018daedc3413085.png', 0, 0, ...getPosition(1, 1))

        // 公司logo
        ctx.drawImage(res[1].path, ...getPosition(2, 2))

        // 公司名称
        ctx.setFontSize(11)
        ctx.fillStyle = '#333'
        ctx.setTextBaseline('top')
        ctx.fillText(params.company, ...getPosition(0, 3))

        // 名字
        ctx.setFontSize(24)
        ctx.fillStyle = '#333';
        ctx.fillText(params.name, ...getPosition(0, 4))

        // 职位
        params.position.split('').map((items, idx) => {
          ctx.setFontSize(12)
          ctx.fillStyle = '#333'
          ctx.fillText(items, ...getPosition(3, 5, idx))
        })
        ctx.rect(...getPosition(2, 6))
        ctx.setFillStyle('#333')
        ctx.fill()

        // Logo背景图
        ctx.drawImage('../../images/carteFavorites/avatar_bg.png', ...getPosition(2, 7))

        // Logo
        ctx.drawImage(res[2].path, ...getPosition(2, 8))

        // 电话
        ctx.drawImage('../../images/carteFavorites/phone.png', ...getPosition(2, 9))
        ctx.setFontSize(10)
        ctx.fillStyle = '#fff'
        ctx.setTextBaseline('top')
        ctx.fillText(params.mobile, ...getPosition(0, 10))

        // 电话
        ctx.drawImage('../../images/carteFavorites/mail.png', ...getPosition(2, 11))
        ctx.setFontSize(10)
        ctx.fillStyle = '#fff'
        ctx.setTextBaseline('top')
        ctx.fillText(params.email, ...getPosition(0, 12))

        ctx.draw(false, function (canvas_res) {
          // console.log(canvas_res)
          wx.canvasToTempFilePath({
            x: 0,
            y: 0,
            width: 500,
            height: 400,
            destWidth: 500,
            destHeight: 400,
            canvasId: 'carte_canvas_' + idx,
            success(canvas_temp_res) {
              // resolve(canvas_temp_res.tempFilePath)
              // console.log(canvas_temp_res)
              wx.uploadFile({
                url: baseUrl + ftp_share_image, // 仅为示例，非真实的接口地址
                filePath: canvas_temp_res.tempFilePath,
                name: 'file',
                formData: {},
                success(upload_res) {
                  // console.log(upload_res)
                  let json_upload_res = JSON.parse(upload_res.data)
                  // resolve(upload_res.data)
                  // console.log(json_upload_res)
                  if (json_upload_res.msg != "success") {
                    app.showTipMsg(res.msg)
                    reject()
                  } else {
                    resolve(json_upload_res.data)
                  }
                },
                fail(upload_err) {
                  // console.log(upload_err)
                  reject(upload_err)
                }
              })
            },
            fail(canvas_temp_err) {
              reject(canvas_temp_err)
            }
          })
        })
      })
    })
    return toTempPath
  },


  // 名片canvas渲染并打开分享遮罩层
  canvasAndShowshare: function (e) {
    const that = this
    const idx = e.currentTarget.dataset.idx
    const CarteList = this.data.CarteList

    var url2 = "/cardshop_api/card_word";
    var params2 = {
      type: 3,
      uid: CarteList[idx].id
    }
    app.HttpPostSend(url2, params2,
      function (result_data) {
        if (result_data.msg != "success") {
          app.showTipMsg(result_data.msg);
        } else {
          if (!!result_data.data) {
            that.setData({
              content: result_data.data.content
            })
          }
        }
      })

    const userInfo = app.globalData.userInfo
    this.setData({
      haveTap: 0,
      haveShare: 0,
    })
    this.setData({
      haveTap: 1,
      haveShare: 1,
      TaskShow: 2,
      shareInfo: {
        carte: CarteList[idx],
        share_id: userInfo.id,
        share_img: CarteList[idx].img
      }
    })
    // that.renderCanvasCarte(idx, CarteList[idx]).then(render_canvas_res => {
    //   // console.log(render_canvas_res)
    //   that.setData({
    //     haveTap: 1,
    //     haveShare: 1,
    //     TaskShow: 2,
    //     shareInfo: {
    //       carte: CarteList[idx],
    //       share_id: userInfo.id,
    //       share_img: render_canvas_res
    //     }
    //   })
    // })
  },

  // 关闭分享遮罩层
  HideShareMask: function () {
    this.setData({
      TaskShow: 0
    })
  },

  showSharePost: function () {
    const that = this
    let CarteInfo = this.data.shareInfo.carte
    CarteInfo.img.src = CarteInfo.img.src.split('?x-oss-process=style/index_mp')[0];
    CarteInfo.comLogo.src = CarteInfo.comLogo.src.split('?x-oss-process=style/goods_skeletonize')[0];
    // console.log("CarteInfo:",CarteInfo)
    wx.navigateTo({
      url: '/pages/sharePost/sharePost?carte_info=' + JSON.stringify(CarteInfo)
    })
  },

  // 点击名片进入名片首页
  showCarte: function (e) {
    const that = this
    const haveTap = this.data.haveTap
    const carte_id = e.detail.carte_id
    if (haveTap == 0) {
      console.log('屏蔽重复点击')
    } else {
      app.globalData.SwitchTabParams = {
        v_id: carte_id
      }
      // wx.switchTab({
      //   url: '/pages/carteShow/carteShow'
      // })
      wx.navigateTo({
        url: '/shopPages/personalShop/personalShop',
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    const that = this
    const shareInfo = this.data.shareInfo
    const carte = this.data.shareInfo.carte
    app.radarAdd(carte.id, 3,'','',app.globalData.userInfo.logo)

    // 发送模板消息-作品被转发通知
    app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 2, '/radarPages/radarCenter/radarCenter?coming_status=1', '您的门店帮扶系统被' + app.globalData.userInfo.username + '转发了', '', '', '')
    if (e.from === 'button') {
      // 来自页面内转发按钮
    }
    if (that.data.content.indexOf("**") != -1) {
      var sharecontent = that.data.content.replace('**', carte.name);
    } else {
      sharecontent = that.data.content;
    }
    return {
      title: sharecontent,
      path: '/pages/carteShow/carteShow?carte_id=' + carte.id + '&share_id=' + shareInfo.share_id,
      imageUrl: shareInfo.share_img,
      complete(res) {
        // console.log(res)
        that.setData({
          haveTap: 1,
          TaskShow: 0
        })
      }
    }
  }
})